//
//  WBComposeTypeView.swift
//  simpleWeibo
//
//  Created by sunmumu on 2019/2/20.
//  Copyright © 2019 孙林. All rights reserved.
//

import UIKit
import pop

/// 撰写微博类型视图
class WBComposeTypeView: UIView {
    /// scrollView
    @IBOutlet weak var scrollView: UIScrollView!
    /// 返回上一页按钮
    @IBOutlet weak var backButton: UIButton!
    /// 返回上一页按钮 CenterX约束
    @IBOutlet weak var backButtonCenterXConstraint: NSLayoutConstraint!
    /// 关闭按钮 CenterX约束
    @IBOutlet weak var closeButtonCenterXConstraint: NSLayoutConstraint!
    /// 完成回调
    private var completionBlock: ((_ clsName: String?) -> ())?
    
    /// 按钮数据数组
    let buttonsInfo = [["imageName": "tabbar_compose_idea", "title": "文字", "clsName": "WBComposeViewController"],
                       ["imageName": "tabbar_compose_photo", "title": "照片/视频"],
                       ["imageName": "tabbar_compose_weibo", "title": "长微博"],
                       ["imageName": "tabbar_compose_lbs", "title": "签到"],
                       ["imageName": "tabbar_compose_review", "title": "点评"],
                       ["imageName": "tabbar_compose_more", "title": "更多", "actionName": "clickMore"],
                       ["imageName": "tabbar_compose_friend", "title": "好友圈"],
                       ["imageName": "tabbar_compose_wbcamera", "title": "微博相机"],
                       ["imageName": "tabbar_compose_music", "title": "音乐"],
                       ["imageName": "tabbar_compose_shooting", "title": "拍摄"]
    ]
    
    class func composeTypeView() -> WBComposeTypeView {
        let nib = UINib.init(nibName: "WBComposeTypeView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as!WBComposeTypeView
        v.frame = UIScreen.main.bounds
        
        v.setupUI()
        
        return v
    }
    
    // 闭包作为方法的参数 传递进去 闭包如果不在当前方法执行, 使用属性记录下来, 在需要的时候执行
    func show(completion: @escaping (_ clsName: String?) -> ()) {
        //记录闭包
        completionBlock = completion
        guard let v = UIApplication.shared.keyWindow?.rootViewController else {
            return
        }
        v.view.addSubview(self)
        
        //添加动画
        showCurrentView()
    }
    
    // MARK: - 监听方法
    @objc func didClick(selectButton: WBComposeTypeButton) {
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        
        for (i, btn) in v.subviews.enumerated() {
            //1缩放动画
            let scaleAnimation: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            
            let scale = (btn == selectButton) ? 2 : 0.2
            scaleAnimation.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            scaleAnimation.duration = 0.25
            
            btn.pop_add(scaleAnimation, forKey: nil)
            
            //2透明度动画 pop动画组:创建多个动画,并直接添加使用,就是动画组
            let alphaAnimation: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            alphaAnimation.toValue = 0.2
            alphaAnimation.duration = 0.5
            
            btn.pop_add(alphaAnimation, forKey: nil)
            
            if i == 0 {
                alphaAnimation.completionBlock = { _, _ in
                    //执行闭包
                    self.completionBlock?(selectButton.clsName as String?)
                }
            }
        
        }
    }
    
    func clickMore(_ : UIButton) {
        //将scrollView 滚动到第二页
        scrollView.setContentOffset(CGPoint(x: scrollView.bounds.width, y: 0), animated: true)
        //底部视图 按钮 设置
        backButton.isHidden = false
        let margin = scrollView.bounds.width / 6
        backButtonCenterXConstraint.constant -= margin
        closeButtonCenterXConstraint.constant += margin
        
        UIView.animate(withDuration: 0.25) {
            self.layoutIfNeeded()
        }
    }
    
    @IBAction func clickBackButton() {
        //将scrollView 滚动到第一页
        scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
        //底部视图 按钮 设置
        backButtonCenterXConstraint.constant = 0
        closeButtonCenterXConstraint.constant = 0
        
        UIView.animate(withDuration: 0.25, animations: {
            self.layoutIfNeeded()
            self.backButton.alpha = 0
        }) { _ in
            self.backButton.isHidden = true
            self.backButton.alpha = 1
        }
        
    }
    
    @IBAction func close() {
//        removeFromSuperview()
        hideButtons()
    }
    
}

// MARK: - 动画方法拓展
private extension WBComposeTypeView {
    
    // MARK: - 隐藏部分动画
    func hideButtons() {
        //获取scrollView的子视图
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        //遍历v 的子视图
        for (i, btn) in v.subviews.enumerated().reversed() {
            //1 创建动画
            let animation : POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            
            //2 设置动画属性
            animation.fromValue = btn.center.y
            animation.toValue = btn.center.y + 350
            animation.springBounciness = 8
            animation.springSpeed = 8
            animation.beginTime = CACurrentMediaTime() + CFTimeInterval(scrollView.subviews.count - i) * 0.025
            
            //3 添加动画
            btn.layer.pop_add(animation, forKey: nil)
            
            if i == 0 {
                animation.completionBlock = { _, _ in
                    self.hideCurrentView()
                }
            }
        }
        
    }
    
    func hideCurrentView() {
        //1 创建动画
        let animation : POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        
        //2 设置动画属性
        animation.fromValue = 1
        animation.toValue = 0
        animation.duration = 0.1
        
        //3 添加动画
        pop_add(animation, forKey: nil)
        
        animation.completionBlock = { _, _ in
            self.removeFromSuperview()
        }
        
    }
    
    // MARK: - 显示部分动画
    /// POPBasicAnimation 基本动画
    func showCurrentView() {
        //1 创建动画
        let animation : POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        
        //2 设置动画属性
        animation.fromValue = 0
        animation.toValue = 1
        animation.duration = 0.5
        
        //3 添加动画
        pop_add(animation, forKey: nil)
        showButtons()
    }
    
    /// POPSpringAnimation 弹力动画
    func showButtons() {
        //获取scrollView的子视图
        let v = scrollView.subviews[0]
        //遍历v 的子视图
        for (i, btn) in v.subviews.enumerated() {
            //1 创建动画
            let animation : POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
    
            //2 设置动画属性
            animation.fromValue = btn.center.y + 350
            animation.toValue = btn.center.y
            animation.springBounciness = 8
            animation.springSpeed = 8
            animation.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025
            
            //3 添加动画
            btn.pop_add(animation, forKey: nil)
        }
    }
}

//private 会让extension 所有的方法都是 私有的
private extension WBComposeTypeView {
    func setupUI() {
        //更新布局约束
        layoutIfNeeded()
        
        //向scrollView 添加视图
        let rect = scrollView.bounds
        
        for i in 0..<2 {
            let v = UIView(frame: rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0))
            //添加6个按钮
            addButtons(v: v, idx: i * 6)
            scrollView.addSubview(v)
        }
        
        //设置scrollView
        scrollView.contentSize = CGSize(width: 2 * rect.width, height: 0)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
        scrollView.isScrollEnabled = false
    }
    
    func addButtons(v: UIView, idx: Int) {
        
        let count = 6
        
        //从 idx开始 添加 count = 6个按钮
        for i in idx..<(idx + count) {
            //判断 i下标 在buttonsInfo数组是否 存在
            if i >= buttonsInfo.count {
                break
            }
            
            //0 创建所需参数
            let dict = buttonsInfo[i]
            guard let imageName = dict["imageName"], let title = dict["title"] else {
                continue
            }
            
            //1 创建
            let btn = WBComposeTypeButton.composeTypeButton(imageName: imageName, title: title)
            
            //2 监听事件
            //oc中写法 NSSelectorFromeString
            if let actionName = dict["actionName"] {
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            } else {
                btn.addTarget(self, action: #selector(didClick(selectButton:)), for: .touchUpInside)
            }
            
            //3 设置 对应的clsName 属性名称
            btn.clsName = dict["clsName"] as NSString?
            
            //4 添加
            v.addSubview(btn)
        }
        
        //布局按钮
        for (i, btn) in v.subviews.enumerated() {
            
            let buttonSize = CGSize(width: 100, height: 100)
            let margin = (v.bounds.width - 3 * buttonSize.width) / 4
            let colu = i % 3
            let x = CGFloat(colu + 1) * margin + CGFloat(colu) * buttonSize.width
            let y = (i > 2) ? (v.bounds.height - buttonSize.height) : 0
            
            btn.frame = CGRect(x: x, y: y, width: buttonSize.width, height: buttonSize.height)
            
        }
        
    }
    
}
